package com.qidian.zl.paper.servlets;

import com.qidian.zl.paper.factory.ServiceFactory;
import com.qidian.zl.paper.pojo.Answer;
import com.qidian.zl.paper.pojo.Field;
import com.qidian.zl.paper.pojo.Paper;
import com.qidian.zl.paper.service.FieldService;
import com.qidian.zl.paper.service.PaperService;
import com.qidian.zl.paper.util.DateUtils;
import com.qidian.zl.paper.util.JsonTools;
import com.qidian.zl.paper.util.StResult;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

@WebServlet(urlPatterns = {"/savePaper","/queryPaper", "/queryById", "/updateStatus", "/getGroupId", "/sub", "/answerList", "/exportAnswer","/deletePaperById"})
public class PaperServlet extends HttpServlet {
    private PaperService paperService = ServiceFactory.getPaperService();
    private FieldService fieldService=ServiceFactory.getFieldService();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String uri = request.getRequestURI();
        if (uri.endsWith("savePaper")) {
            savePaper(request, response);
        } else if (uri.endsWith("queryPaper")) {
            queryByPaper(request, response);
        } else if (uri.endsWith("queryById")) {
            queryById(request, response);
        } else if (uri.endsWith("updateStatus")) {
            updateStatus(request, response);
        } else if (uri.endsWith("getGroupId")) {
            getGroupId(request, response);
        } else if (uri.endsWith("sub")) {
            sub(request, response);
        } else if (uri.endsWith("answerList")) {
            answerList(request, response);
        }else if(uri.endsWith("exportAnswer")){
            exportAnswer(request,response);
        } else if (uri.endsWith("deletePaperById")) {
            deletePaperById(request, response);
        }
    }

    private void exportAnswer(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 创建一个工作簿
        Workbook wb=new XSSFWorkbook();
        // 创建一个sheet
        Sheet sheet=wb.createSheet("问卷数据");
        long paperId=Long.parseLong(request.getParameter("paperId"));
        // 查询所有的域
        StResult fieldResult = fieldService.queryByPaperId(paperId);
        List<Field> fields = fieldResult.getData();
        // 设置表头

        Row row = sheet.createRow(0);
        //创建一个新行
        for (int i=0;i<fields.size();i++){
            //创建一个新的单元格
            Cell cell = row.createCell(i);
            // 给单元格设置数据
            cell.setCellValue(fields.get(i).getFieldName());
        }
        //查询数据 (默认每页100条)
        //查询第一页数据
        StResult result = paperService.queryAnswer(paperId, 1, 100);
        //计算最大页码
        int total = Integer.parseInt(result.getObj().toString());
        int maxPageNum=(int)Math.ceil(total*1.0/100);
        //循环操作，第一页不需要查询，直接操作，所以使用do  whiel
        int i=0;
        do {
            List<Map> data = result.getData();
            for (int j = 0;j < data.size();j++){
                Map map = data.get(j);
                // 创建一个新行
                row = sheet.createRow((j+1));
                for(int x = 0;x<fields.size();x++){
                    // 创建一个新的单元格
                    Cell cell = row.createCell(x);
                    Field a = fields.get(x);
                    String key = "";
                    switch (a.getFieldType()){
                        case 2:
                            // 单行文本
                            key="text_"+a.getFieldId();
                            break;
                        case 3:
                            //多行文本
                            key="textarea_"+a.getFieldId();
                            break;
                        case 4:
                            // 单选按钮
                            key="radio_"+a.getFieldId();
                            break;
                        case 5:
                            // 多选按钮
                            key="checkbox_"+a.getFieldId();
                            break;
                    }
                    // 给单元格设置数据
                    cell.setCellValue(map.get(key)+"");
                }
            }
            i++;
        }while(i < maxPageNum);
        // 设置响应头信息，在其中设置好文件名
        response.setHeader("Content-Disposition","attachment; filename=answer-list.xlsx");
        // 得到输出流（这个输出流就指向客户端）
        ServletOutputStream out = response.getOutputStream();
        // 输出工作簿到输出流
        wb.write(out);
    }


    private void answerList(HttpServletRequest request, HttpServletResponse response) throws IOException {
        StResult result = null;
        int page =1;
        int size = 10;
        try{page = Integer.parseInt(request.getParameter("page"));}catch (Exception e){}
        try{size = Integer.parseInt(request.getParameter("size"));}catch (Exception e){}

        try {
            Long paperId = Long.parseLong(request.getParameter("paperId"));
            //查询
           result= paperService.queryAnswer(paperId, page, size);

        } catch (NumberFormatException e) {
            e.printStackTrace();
            result = StResult.fail("请传入正确的问卷编号");
        }
        // 输出result对象
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JsonTools.obj2String(result));
    }
    //添加
    private void sub(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Enumeration<String> names = request.getParameterNames();
        // 提前定义好paperId和groupId。
        long paperId = -1;
        String groupId = null;
        // 准备一个Answer列表
        List<Answer> answers = new ArrayList<>();
        // 遍历请求参数名字的列表
        while (names.hasMoreElements()) {
            // 获取请求参数的名字
            String name = names.nextElement();
            //特殊处理paperId和groupId
            if (name.equals("paperId")) {
                paperId = Long.parseLong(request.getParameter(name));
            } else if (name.equals("groupId")) {
                groupId = request.getParameter("groupId");
            } else {
                // 使用"_"将名字分开。数组的第二个元素就是这个域的id
                String[] nameInfo = name.split("_");
                if (nameInfo != null && nameInfo.length == 2) {
                    //取出filedId
                    Long fileId = Long.parseLong(nameInfo[1]);

                    // 根据name取出请求参数的值。 无论是一个值还是多个值，取出的都是数组

                    String[] texts = request.getParameterValues(name);
                    // 准备一个缓冲字符串存储提交的答案
                    StringBuilder answerText = new StringBuilder("");
                    // 遍历数组将答案使用"&"连接起来。
                    for (String text : texts) {
                        answerText.append(text + "&");
                    }
                    // 删除多余的"&"符号
                    answerText.deleteCharAt(answerText.length() - 1);
                    // 创建一个answer对象
                    Answer answer = new Answer();
                    answer.setAnswerText(answerText.toString());
                    answer.setAnswerTime(DateUtils.getNow());
                    answer.setFieldId(fileId);
                    answer.setPaperId(paperId);
                    answer.setGroupId(groupId);
                    //将answer加入列表
                    answers.add(answer);
                }
            }
        }// 调用service保存
        paperService.subPaper(paperId, answers);
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JsonTools.obj2String(StResult.ok("提交成功")));

    }


    private void getGroupId(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 使用UUID生成一个唯一标志，放在StResult的msg中，返回
        String groupId = UUID.randomUUID().toString().replace("-", "");
        // 输出result对象
        /*Cookie[] cookies = request.getCookies();
        String groupId = null;
        if (cookies!=null&&cookies.length>0){
            for (Cookie cookie:cookies) {
                if ("groupId".equals(cookie.getName())) {
                    groupId = cookie.getValue();
                    break;
                }
            }
        }*/
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JsonTools.obj2String(StResult.ok(groupId)));
    }


    private void updateStatus(HttpServletRequest request, HttpServletResponse response) throws IOException {
        StResult result = null;
        try {
            Long paperId = Long.parseLong(request.getParameter("paperId"));
            Integer paperStatus = Integer.parseInt(request.getParameter("paperStatus"));
            int updateStatus = paperService.updateStatus(paperId,paperStatus);
            if (updateStatus == 1) {
                result = StResult.ok();
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = StResult.fail();
        }
        // 输出result对象
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JsonTools.obj2String(result));

    }


    private void queryById(HttpServletRequest request, HttpServletResponse response) throws IOException {
        StResult result = null;
        try {
            Long paperId = Long.parseLong(request.getParameter("paperId"));
            Paper paper = paperService.queryById(paperId);
            //System.out.println(paper);
            result = StResult.ok();
            result.setObj(paper);
        } catch (NumberFormatException e) {
            e.printStackTrace();
            result = StResult.fail("请传入正确的问卷编号");
        }// 输出result对象
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JsonTools.obj2String(result));
    }

    /**
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void deletePaperById(HttpServletRequest request, HttpServletResponse response) throws
            ServletException, IOException {
        Long paperId = Long.valueOf(request.getParameter("paperId"));
        StResult result = null;
        int delete = paperService.delete(paperId);
        if (delete == 1) {
            result = StResult.ok("ok");

        } else {
            result = StResult.fail("error");
        }
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JsonTools.obj2String(result));


    }

    /**
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void savePaper(HttpServletRequest request, HttpServletResponse response) throws
            ServletException, IOException {
        StResult result = null;
        Long paperId = -1L;
        try {
            paperId = new Long(request.getParameter("paperId"));
        } catch (Exception e) {
        }
        String paperTitle = request.getParameter("paperTitle");
        String paperDesc = request.getParameter("paperDesc");
        if (paperTitle == null || "".equals(paperTitle)) {
            result = StResult.fail("问卷标题不能为空");
        } else {
            Paper paper = new Paper();
            paper.setPaperId(paperId);
            paper.setPaperTitle(paperTitle);
            paper.setPaperDesc(paperDesc);
            paper.setPaperCreated(DateUtils.getNow());
            System.out.println(paper.toString());
            paperId = paperService.saveOrUpdate(paper);

            if (paperId == -1) {
                result = StResult.fail("保存或修改失败");
            } else {
                result = StResult.ok(paperId + "");
            }
        }
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JsonTools.obj2String(result));
    }

    /**
     * 查询全部query
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void query(HttpServletRequest request, HttpServletResponse response) throws
            ServletException, IOException {
        int page = 1;
        int size = 10;
        try {
            page = Integer.parseInt(request.getParameter("page"));
        } catch (Exception e) {
        }
        try {
            size = Integer.parseInt(request.getParameter("size"));
        } catch (Exception e) {
        }
        List<Paper> papers = paperService.query(page, size);
        int total = paperService.queryTotal();
        StResult result = StResult.ok("", total, papers);

        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JsonTools.obj2String(result));

    }

    /**
     * 按条件查询paper
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void queryByPaper(HttpServletRequest request, HttpServletResponse response) throws
            ServletException, IOException {
        int page = 1;
        int size = 10;
        try {
            page = Integer.parseInt(request.getParameter("page"));
        } catch (Exception e) {
        }
        try {
            size = Integer.parseInt(request.getParameter("size"));
        } catch (Exception e) {
        }
        Paper paper = new Paper();
        String paperTitle = request.getParameter("paperTitle");
        paper.setPaperTitle(paperTitle);
        try {
            paper.setPaperStatus(Integer.parseInt(request.getParameter("paperStatus")));
            if (paper.getPaperStatus().equals(new Integer(0))) {
                paper.setPaperStatus(null);
            }
        } catch (NumberFormatException e) {
        }
        String startTime = request.getParameter("startTime");
        String endTime = request.getParameter("endTime");
        StResult result = paperService.queryByPage(page, size, paper, startTime, endTime);

        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JsonTools.obj2String(result));

    }
}
